using System.Collections.Generic;
using UnityEngine;
using static WaterCylinder.Object;
using static WaterCylinder.Resource;

public class DropItem : MonoBehaviour
{   
    public static DropItem CreatDropItem(Entity owner , Item item, Vector2 pos = default){
        GameObject obj = Creat(GetPrefab("DefaultObject/DropItem"));
        if(owner == null){
            obj.transform.position = default;
        }else{
            if(pos == default){
                obj.transform.position = owner.dropPos;
            }else{
                obj.transform.position = pos;
            }
        }
        obj.transform.localPosition = pos;
        obj.GetComponent<SpriteRenderer>().sprite = item.sprite;
        DropItem di = obj.GetComponent<DropItem>();
        di.contactIgnoreCollisionDistance = contactIgnoreCollisionDistanceDefault;
        di.item = Instantiate(item);
        di.item.owner = owner;
        di.item.OnDrop(owner);
        di.item.state = ItemState.Drop;
        obj.name = di.item.name;
        return di;
    }

    public static readonly float contactIgnoreCollisionDistanceDefault = 1;

    /// <summary>
    /// 物品对象
    /// </summary>
    public Item item;
    
    /// <summary>
    /// 解除对owner碰撞箱的无视需要的相对距离
    /// </summary>
    public float contactIgnoreCollisionDistance = 1;

    [SerializeField]
    private List<string> ignoreTags = new List<string>();
    public bool IgnoreCheck(string tag){
        return ignoreTags.Contains(tag);
    }
    
    /// <summary>
    /// 掉落物消失
    /// </summary>
    public void Disappear(){
        Delete(gameObject);
    }

    private void Start() {
        if(item.owner){//创建时无视owner的碰撞
            Physics2D.IgnoreCollision(item.owner.GetComponent<Collider2D>(), GetComponent<Collider2D>());
        }
    }

    private void FixedUpdate() {
        //和owner的距离小于规定距离时，将规定距离设为0并且重启碰撞检测
        if(contactIgnoreCollisionDistance > 0 && item.owner != null){
            Vector2 dis = transform.position - item.owner.transform.position;
            if(dis.magnitude > contactIgnoreCollisionDistance){
                contactIgnoreCollisionDistance = 0;
                Physics2D.IgnoreCollision(item.owner.GetComponent<Collider2D>(), GetComponent<Collider2D>(), false);
            }
        }
    }

}
